package com.example.yin.utilproject;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

/**
 * 从鸿洋大神那里学习到的绘制圆角/圆形图片的方法（博客地址：http://blog.csdn.net/lmj623565791/article/details/41967509）
 * 这里用的是BitmapShader实现，另外也可用Xfermode实现，鸿洋大神也有专门的文章
 * Created by Yin on 2016/5/26.
 */
public class RoundImageView extends ImageView {

    private static final int TYPE_CIRCLE = 0;
    private static final int TYPE_ROUND = 1;
    private static final int DEFAULT_BORDER_RADIUS = 10;

    private int type;
    private int borderRadius;
    private Paint bitmapPaint;
    private int width;
    private int radius;
    private String TAG = "yzh";


    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        /**
         * 获取自定义属性的值
         */
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);

        type = typedArray.getInt(R.styleable.RoundImageView_type, TYPE_CIRCLE);
        borderRadius = typedArray.getDimensionPixelSize(R.styleable.RoundImageView_borderRadius, DEFAULT_BORDER_RADIUS);

        typedArray.recycle();

        bitmapPaint = new Paint();
        bitmapPaint.setAntiAlias(true);

    }

    /**
     * 如果用户设置的type是circle，强制统一view的宽高一致，取最小值
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.d(TAG, "onMeasure: ");
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (type == TYPE_CIRCLE) {
            width = Math.min(getMeasuredWidth(), getMeasuredHeight());
            radius = width / 2;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.d(TAG, "onDraw: ");
        if (getDrawable() == null) {
            return;
        }

        initPaint();
        if (type == TYPE_CIRCLE) {
            canvas.drawCircle(radius, radius, radius, bitmapPaint);
        } else if (type == TYPE_ROUND){
            canvas.drawRoundRect(rectF,borderRadius,borderRadius,bitmapPaint);
        }
    }

    RectF rectF;
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.d(TAG, "onSizeChanged: ");
        super.onSizeChanged(w, h, oldw, oldh);
        rectF = new RectF(0, 0, getWidth(), getHeight());
    }

    /**
     * 给画笔设置Shader，Shader里包含了缩放适当后的图片
     */
    private void initPaint() {
        Drawable drawable = getDrawable();
        Bitmap bitmap = drawableToBitmap(drawable);
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        float scale = 1.0f;
        /**
         * 如果是圆，把图片缩放到刚好填满view的大小
         * 如果是圆角矩形，也至少要让最窄的边填满
         */
        if (type == TYPE_CIRCLE) {
            int bitmapSize = Math.min(bitmap.getWidth(), bitmap.getHeight());
            scale = width * 1.0f / bitmapSize;
        } else if (type == TYPE_ROUND) {
            scale = Math.max(getMeasuredWidth() * 1.0f / bitmap.getWidth(), getMeasuredHeight() * 1.0f / bitmap.getHeight());
        }
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        bitmapShader.setLocalMatrix(matrix);
        bitmapPaint.setShader(bitmapShader);

    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        int i = 0;
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }
}
